package com.wanxi.filter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")//拦截了所有访问后台的地址
//@WebFilter("/back/*")
public class MyFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        req.setCharacterEncoding("UTF-8");
        res.setCharacterEncoding("UTF-8");
        //我们只需要拦截接口地址以back开头的即可，其他都不需要拦截
        // 怎么得到前端访问后台的地址呢？
        String path = req.getServletPath();
        if (path.startsWith("/back/")) {
            //判断用户是否已经登录
            String username = (String) req.getSession().getAttribute("username");
            if (username == null) {
                //标识没有登录，则跳转到登录页面
                res.sendRedirect("/html/login.html");
//                res.getWriter().println(JSONObject.toJSONString(ResultModel.error()));
            } else {
                chain.doFilter(req, res);//已经登录后则直接放行
            }
        } else {
            chain.doFilter(req, res);//不需要判断登录也直接放行
        }
    }
}
